#include <func.h>

// epoll实现取消重现（实际是增加新的连接）
int main(int argc, char *argv[])
{
    ARGS_CHECK(argc, 3);
    int sfd = socket(AF_INET, SOCK_STREAM, 0);
    ERROR_CHECK(sfd, -1, "socket");
    struct sockaddr_in addr;
    addr.sin_addr.s_addr = inet_addr(argv[1]);
    addr.sin_family = AF_INET;
    addr.sin_port = htons(atoi(argv[2]));
    int ret = connect(sfd,(struct sockaddr*)&addr,sizeof(addr));
    // 创建一个epoll
    int epfd = epoll_create(1);
    ERROR_CHECK(epfd, -1, "epoll");
    // 创建一个epoll结构体
    struct epoll_event event;
    event.data.fd = STDIN_FILENO;
    event.events = EPOLLIN;
    epoll_ctl(epfd, EPOLL_CTL_ADD, STDIN_FILENO, &event); // 把stdin以读时间加入监听
    event.data.fd = sfd;
    event.events = EPOLLIN;
    epoll_ctl(epfd, EPOLL_CTL_ADD, sfd, &event); // 把已经连接的socket以读的事件加入监听；
    char buf[4096] = {0};
    struct epoll_event readyArr[2];

    while (1)
    {
        int readyNum = epoll_wait(epfd, readyArr, 2, -1); // epoll_wait的返回值是就绪事件的个数；
        puts("epoll_wair returns");
        for (int i = 0; i < readyNum; i++)
        {
            if (readyArr[i].data.fd == STDIN_FILENO)
            {
                
                bzero(buf, sizeof(buf));
                int ret = read(STDIN_FILENO, buf, sizeof(buf));
                if (ret == 0)
                {
                    goto end;
                }
                send(sfd, buf, strlen(buf), 0);
            }
           
            else if(readyArr[i].data.fd==sfd)
            {
                bzero(buf,sizeof(buf));
                int ret = recv(sfd,buf,sizeof(buf),0);
                if(ret ==0)
                {
                    printf("你是个好人\n");
                    goto end;
                    
                }
                
                puts(buf);
            }
        }
    }
end:
close(sfd);
    return 0;
}